# import os
# import pandas as pd
# from scipy.spatial import cKDTree
# from collections import Counter
# import math
# from datetime import datetime, timedelta
# from reading import read_all_csv_in_folder
# from TrImpute import  TreeNode
# from TrImpute import  generate_tree
# from  TrImpute import  nextpoint
# from tqdm import tqdm
# threshold_distance1 =5
# max_depth = 10
# threshold_distance =2
# time_index=0
# lon_index=1
# lat_index=2
# alt_index=3
# speed_index=4
# threshold_angle = 0.5
#
# data_file = './datasets/allcsv'
# data = read_all_csv_in_folder(data_file)
# def impute(inputdata):
#   imputed_data = []
#   for  traj_data in inputdata:
#     # print("imputing trackId:",traj["trackId"])
#     # print("imputing data" ,traj["trackData"])
#     traj = pd.DataFrame( traj_data["trackData"], columns=["timestamp", "longitude", "latitude", "altitude", "speed"])
#     # print(traj)
#
#
#     T = pd.DataFrame(columns=["time", "lon", "lat"])
#     for i in tqdm(range(len(traj) - 1)):
#
#         s = traj.iloc[i]
#         destination = traj.iloc[i + 1]
#         time0=s[time_index]
#         time1=destination[time_index]
#         # time0 = datetime.strptime(time0, '%Y-%m-%d %H:%M:%S')
#         # time1 = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')
#         # print(destination)
#         # print(s)
#
#         root_value = (s[lon_index], s[lat_index])
#         # T.append(root_value)
#         distance = math.sqrt((destination[lon_index] - s[lon_index]) ** 2 + (destination[lat_index] - s[lat_index]) ** 2)
#
#         # print(distance)
#         if distance < threshold_distance1:
#             continue
#         # print(distance)
#         root = TreeNode(root_value)
#
#
#         reference_point = (destination[lon_index], destination[lat_index])
#         dlon = float((reference_point[0] - root_value[0]) / 10)
#         dlat = float((reference_point[1] - root_value[1]) / 10)
#
#
#         # print(dlon,dlat)
#         # (root, data, generate_children, reference_point, threshold_distance, threshold_angle, max_depth, output_dir, current_depth=0, visited_points=None)
#         # print(reference_point, root_value)
#         t=generate_tree(root, data, nextpoint, reference_point, threshold_distance, threshold_angle,dlon,dlat,max_depth=max_depth, )
#         t_df = pd.DataFrame(t, columns=["lon", "lat"])
#
#         num_nodes = len(t_df)
#         if len(t_df) != 0:
#            time_step = (time1 - time0) / num_nodes
#
#         # 为每个节点添加 time 属性
#            t_df['time'] = [time0 + i * time_step for i in range(num_nodes)]
#            t_df = t_df[['time', 'lon', 'lat']]
#            # print(t_df)
#         T = pd.concat([T, t_df], ignore_index=True)
#     print(len(T))
#
#     if len(T) != 0:
#        new_traj_data = {
#             "trackId": traj_data["trackId"],
#             "trackData": T.values.tolist()  # 将 DataFrame 转换为列表形式
#         }
#
#     # 将新的轨迹数据添加到 imputed_data 列表中
#        imputed_data.append(new_traj_data)
#   return  imputed_data
#     # print(T)
#     # # new_points_df = pd.DataFrame(T, columns=["time", "lon", "lat"])
#     #
#     # # new_points_df = pd.DataFrame(T, columns=["lon", "lat"])
#     # T.to_csv(os.path.join(file_output_dir, 'new_points.csv'), index=False)
#
import os
import pandas as pd
from scipy.spatial import cKDTree
from collections import Counter
import math
from datetime import datetime, timedelta
from imputation.reading import read_all_csv_in_folder
from imputation.TrImpute import TreeNode
from imputation.TrImpute import generate_tree
from imputation.TrImpute import nextpoint
from tqdm import tqdm
from imputation.config import Config

threshold_distance1 = Config.threshold_distance1

threshold_distance = Config.threshold_distance
time_index = Config.time_index
lon_index = Config.lon_index
lat_index = Config.lat_index
alt_index = Config.alt_index
speed_index = Config.speed_index
threshold_angle = Config.threshold_angle
data_file = Config.data_file
data = read_all_csv_in_folder(data_file)

def impute(inputdata, ):
    imputed_data = []
    for traj_data in inputdata:
        traj = pd.DataFrame(traj_data["trackData"], columns=["timestamp", "longitude", "latitude", "altitude", "speed"])
        T = []
        for i in range(len(traj) - 1):
        # for i in tqdm(range(len(traj) - 1)):

            s = traj.iloc[i]
            destination = traj.iloc[i + 1]
            time0 = s.iloc[time_index]
            time1 = destination.iloc[time_index]

            root_value = (s.iloc[lon_index], s.iloc[lat_index])
            distance = math.sqrt((destination.iloc[lon_index] - s.iloc[lon_index]) ** 2 + (destination.iloc[lat_index] - s.iloc[lat_index]) ** 2)

            if distance < threshold_distance1:
                continue

            root = TreeNode(root_value)
            reference_point = (destination.iloc[lon_index], destination.iloc[lat_index])
            max_depth = int(distance)
            print(max_depth)

            dlon = float((reference_point[0] - root_value[0]) / max_depth)
            dlat = float((reference_point[1] - root_value[1]) / max_depth)

            t = generate_tree(root, traj, nextpoint, reference_point, threshold_distance, threshold_angle, dlon, dlat, max_depth=max_depth, )
            t_df = pd.DataFrame(t, columns=["lon", "lat"])

            num_nodes = len(t_df)
            if len(t_df) != 0:
                time_step = (time1 - time0) / num_nodes

                # 为每个节点添加 time、lon、lat、altitude 和 speed 属性
                for j in range(num_nodes):
                    interpolated_time = time0 + j * time_step
                    interpolated_lon = t_df.iloc[j]['lon']
                    interpolated_lat = t_df.iloc[j]['lat']
                    interpolated_alt = s.iloc[alt_index]  # 假设 altitude 在插值过程中保持不变
                    interpolated_speed = s.iloc[speed_index]  # 假设 speed 在插值过程中保持不变

                    T.append({
                        "timestamp": interpolated_time,
                        "longitude": interpolated_lon,
                        "latitude": interpolated_lat,
                        "altitude": interpolated_alt,
                        "speed": interpolated_speed
                    })

        if len(T) != 0:
            new_traj_data = {
                "trackId": traj_data["trackId"],
                "trackData": T  # 直接使用 T 列表作为 trackData
            }

            # 将新的轨迹数据添加到 imputed_data 列表中
            imputed_data.append(new_traj_data)

            # 将 T 保存为 JSON 格式



    return imputed_data

# 示例调用
# imputed_data = impute(data, './output')

